<template>
  <div>
    <div class="search-result">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          :error.sync="error"
          error-text="加载失败，请稍后重试"
        >
          <van-cell v-for="(item,index) in list" 
              :key="index" 
              :title="item.title" />
        </van-list>
    </div>
  </div>
</template>

<script>
import {getSearchResult} from '@/api/search'
export default {
    name:'SearchResult',
    props:{
      search_text:{
        type:String,
        required:true
      }
    },
    data() {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      perPage: 20,
      error: false
    };
  },
  methods: {
    async onLoad() {
      //1请求获取数据
      try{
        const {data} = await getSearchResult({
          page: this.page,//页码
          per_page: this.perPage,//每页大小
          q:this.search_text //查询关键词
        })
          //2将数据添加到数组列表
          const {results} = data.data
          this.list.push(...results)
          //3将本次加载中的loading 关闭
          this.loading = false
          //4判断是否有数据
          if(results.length){
            //  有，则更新获取下一页数据的页码
            this.page++
          }else{
            //  没有，则将加载状态finished 设置为结束
            this.finished = true
          }
      }catch(err){
          //展示加载失败的提示状态
          this.error = true
          //加载失败了同时关闭loading
          this.loading = false
      }
      
    },
  },
}
</script>

<style>

</style>